package com.wisevar.thirdplatform.gateway.config.openapi;


import com.wisevar.thirdplatform.gateway.exception.BaseException;
import com.wisevar.thirdplatform.gateway.exception.ParamException;
import com.wisevar.thirdplatform.gateway.model.common.ApiResult;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * openapi 异常统一处理
 */
@ControllerAdvice(basePackages = {"com.wisevar.thirdplatform.gateway.controller.openapi"})
public class OpenApiExceptionHandler {


    /**
     * 业务相关异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public ApiResult<Object> businessExceptionHandler(HttpServletRequest request, BaseException e) {
        return ApiResult.build(e.getResultCode().getCode(), e.getMessage());
    }

    /**
     * 参数相关异常(throw new)
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = ParamException.class)
    @ResponseBody
    public ApiResult<Object> paramExceptionHandler(HttpServletRequest request, ParamException e) {
        return ApiResult.paramError(e.getMessage());
    }

    /**
     * 参数校验异常处理 (@RequestBody注解抛出)
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ApiResult<Object> validException(MethodArgumentNotValidException ex) {
        StringBuilder stringBuilder = new StringBuilder();
        for (FieldError error : ex.getBindingResult().getFieldErrors()) {
            //stringBuilder.append(error.getField());
            stringBuilder.append(error.getDefaultMessage()).append(",");
        }
        String msg = stringBuilder.substring(0, stringBuilder.length() - 1);
        return ApiResult.paramError(msg);
    }

    /**
     * 参数校验异常处理 (@RequestParam注解抛出)
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ApiResult<Object> handleBindException(BindException ex) {
        StringBuilder stringBuilder = new StringBuilder();
        for (FieldError error : ex.getBindingResult().getFieldErrors()) {
            stringBuilder.append(error.getDefaultMessage()).append(",");
        }
        String msg = stringBuilder.substring(0, stringBuilder.length() - 1);
        return ApiResult.paramError(msg);
    }


}
